package com.zhenhe.core.modules.service;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhenhe.api.exception.ApiAuthenticationException;
import com.zhenhe.api.login.APILoginUtil;
import com.zhenhe.core.common.service.CrudService;
import com.zhenhe.core.common.utils.IdGen;
import com.zhenhe.core.entity.TUserEntity;
import com.zhenhe.core.modules.dao.TUserDao;

/**
 * 后台用户管理service
 * @author Administrator
 *
 */
@Service
@Transactional
public class TUserService extends CrudService<TUserDao, TUserEntity>{
	
	@Value(value="${apiExpiration}")
	private String expiration;
	
	private static final Logger log = LoggerFactory.getLogger(TUserService.class);
	
	/**
	 * 判断用户名是否存在
	 * @param user
	 * @return 
	 */
	public boolean isUserExist(TUserEntity systemUser){
		return dao.isUserExist(systemUser) != null;
	}

	public TUserEntity getMemberToken(String loginToken) {
		Map<String, Object> param =  new HashMap<String, Object>();
		param.put("loginToken", loginToken);
		//过期时间设置，默认2小时
		long expiration = 2 * 60 * 60 * 1000;
		try{
			expiration = Long.valueOf(this.expiration) * 60 * 60 * 1000;
		}catch(Exception e){
			log.error("api过期时间设置错误：{}",e.getMessage());
		}
		TUserEntity member = dao.getToken(param);
		//判断token是否正确
		if(member==null){
			throw new ApiAuthenticationException(APILoginUtil.unAuthorityJsonString());
		}
		//判断是否超时
		//TODO 待删除
			Long tokenTime = member.getTokenTime();
			if(tokenTime==null){
				tokenTime = 0l;
			}
			if(System.currentTimeMillis()>(tokenTime + expiration)){
				//超时
				throw new ApiAuthenticationException(APILoginUtil.authorityTimeoutJsonString());
			}
		param.remove("loginToken");
		param.put("id", member.getId());
		param.put("tokenTime", System.currentTimeMillis());
		//更新登陆时间
		dao.updateToken(param);
		return member;
	}

	public TUserEntity findMember(String hex) {
		//账号密码判定
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cellPhone", hex);
		TUserEntity member = dao.findMember(map);
		return member;
	}
	
	public TUserEntity findLoginUser(String account) {
		//账号密码判定
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("account", account);
		TUserEntity user = dao.findLoginUser(map);
		return user;
	}
	/**
	 * 更新token
	 * @param id
	 */
	private String loginToToken(Integer id){
		if(id==null){
			throw new ApiAuthenticationException("id不能为null");
		}
		String uuid = IdGen.uuid();
		Map<String, Object> param =  new HashMap<String, Object>();
		param.put("loginToken", uuid);
		param.put("id", id);
		param.put("tokenTime", System.currentTimeMillis());
		dao.updateToken(param);
		return uuid;
	}
	public String successLogin(TUserEntity member){
		return loginToToken(member.getId());
	}
}
